<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
	String basePath = "/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/">
<!-- 下拉框 -->
<link rel="stylesheet" href="static/ace/css/chosen.css" />

<link href="plugins/kindeditor/themes/simple/simple.css" type="text/css"
	rel="stylesheet">
<link href="plugins/kindeditor/themes/default/default.css"
	rel="stylesheet">
<link
	href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"
	rel="stylesheet">
<link href="static/styles/base.css" rel="stylesheet">
<style>
.f0{font-size:0;}
td {
	vertical-align: middle !important;
}
</style>
<!-- jsp文件头和头部 -->
<%@ include file="../index/top.jsp"%>
</head>
<body class="no-skin">
	<!-- /section:basics/navbar.layout -->
	<div class="main-container" id="main-container">
		<!-- /section:basics/sidebar -->
		<div class="main-content">
			<div class="main-content-inner">
				<div class="page-content">
					<div class="row">
						<div class="col-xs-12">
							<form action="period/${msg }.do" name="goodsForm" id="goodsForm"
								method="post">
								<div id="zhongxin" style="padding-top: 13px;">
									<input type="hidden" name="countId" id="countId" /> <input
										type="hidden" id="count" value="${spec.area_goods_count_id }" />
									<input type="hidden" name="specTimeId" id="specTimeId"
										value="${pd.specTimeId }" /> <input type="hidden" id="goodsId"
										value="${pd.goodsId }" /> <input type="hidden" id="timeId"
										value="${pd.timeId }" /> <input type="hidden" id="specId"
										value="${spec.goods_spec_id }" /> <input type="hidden"
										id="base_id" value="${pd.base_id }" /> <input type="hidden"
										id="pic" value="${spec.picture}" /> <input type="hidden"
										id="num" value="${num }" />
									<table id="table_report1"
										class="table table-striped table-bordered table-hover">
										<tr>
											<td
												style="width: 100px; text-align: right; padding-top: 13px;">绑定商品:
											</td>
											<td><a href="javascript:void(0)" onclick="areaGoods();">选择区域商品</a>
												<span id="gS"></span></td>
										</tr>
										<tr>
											<td
												style="width: 100px; text-align: right; padding-top: 13px;">库存:</td>
											<td><input type="number" name="stock_num" id="stock_num"
												value="${spec.stock_num }" maxlength="11" min="0"
												style="width: 98%;" /></td>
										</tr>
										<tr>
											<td
												style="width: 100px; text-align: right; padding-top: 13px;">库存警告:</td>
											<td><input type="number" name="stock_warn_num"
												id="stock_warn_num" value="${spec.stock_warn_num }"
												maxlength="11" min="0" style="width: 98%;" /></td>
										</tr>
										<tr>
											<td
												style="width: 100px; text-align: right; padding-top: 13px;">销售价:</td>
											<td><input type="number" name="price" id="price"
												value="${spec.price }" maxlength="11" min="0"
												style="width: 98%;" /></td>
										</tr>
										<tr>
											<td
												style="width: 100px; text-align: right; padding-top: 13px;">商品已售数量:</td>
											<td><input type="number" name="sale_num" id="sale_num"
												value="${spec.sale_num }" maxlength="11" min="0"
												style="width: 98%;" /></td>
										</tr>
										<tr>
											<td
												style="width: 100px; text-align: right; padding-top: 13px;">最低起售数量:</td>
											<td><input type="number" name="min_shop_num"
												id="min_shop_num" value="${spec.min_shop_num }"
												maxlength="11" min="0" style="width: 98%;" /></td>
										</tr>
										<tr>
											<td
												style="width: 100px; text-align: right; padding-top: 13px;">最高起售数量:</td>
											<td><input type="number" name="max_shop_num"
												id="max_shop_num" value="${spec.max_shop_num }"
												maxlength="11" min="0" style="width: 98%;" /></td>
										</tr>
										<tr>
											<td
												style="width: 110px; text-align: right; padding-top: 13px;">商品权益周期
												(月):</td>
											<td><input type="number" name="equity_cycle"
												id="equity_cycle" value="${spec.equity_cycle }"
												maxlength="11" min="1" style="width: 98%;" /></td>
										</tr>
										<tr>
											<td
												style="width: 100px; text-align: right; padding-top: 13px;">截止使用时间:
											</td>
											<td><span class="dib vm">截止使用时间:&nbsp;</span><input
												id="end_use_time" name="end_use_time"
												placeholder="请选择预计收获时间" value="${spec.end_use_time }" /></td>
										</tr>
									
									</table>
									<table id="table_report2"
										class="table table-striped table-bordered table-hover">
										<c:if
											test="${harvestList !=null && harvestList !='' && harvestList !='[]'}">
											<thead>
												<tr>
													<td class="w100 tr">添加收获参数</td>
													<td><a
														class="ion-ios-plus-outline f20 dib btnAddHarvest"
														id="plus" href="javascript:;"></a></td>
												</tr>
											</thead>
											<tbody class="harvest">
												<c:choose>
													<c:when test="${not empty harvestList}">
														<c:forEach items="${harvestList}" var="p" varStatus="vs">
															<tr>
																<td class="w100 tr aa">第${vs.index+1}阶段:</td>
																<td><input type="hidden" name="harvestId" value="${p.id}" />
																	<div class="container-fluid">
																		<div class="row f0">
																			<div class="dib vm">
																				<span
																					class="ion-ios-minus-outline btn-minus f20 dib btnDeleteHarvest"></span>
																			</div>
																			<div class="dib vm w300 ml20">
																				<input type="text" class="form-control"
																					name="yields" placeholder="请输入预计产量,只支持数字"
																					value="${p.yields }">
																			</div>
																			<div class="dib vm w300 ml20">
																				<input type="text" class="form-control times"
																					id="times${vs.index+1}" name="times"
																					value="${p.times }" readonly="readonly" placeholder="请选择收获时间节点">
																				<%-- <div class="form-control times" id="times${vs.index+1}" name="times">${p.times }</div> --%>
																			</div>
																		</div>
																	</div></td>
															</tr>
														</c:forEach>
													</c:when>
												</c:choose>
											</tbody>
										</c:if>
										<c:if test="${harvestList ==null || harvestList =='[]'}">
											<thead>
												<tr>
													<td class="w100 tr">添加收获参数</td>
													<td><a
														class="ion-ios-plus-outline f20 dib btnAddHarvest"
														id="plus" href="javascript:;"></a></td>
												</tr>
											</thead>
											<tbody class="harvest">
												<tr>
													<td class="w100 tr aa">第1阶段:</td>
													<td>
													<div class="container-fluid">
														<div class="row f0">
															<div class="dib vm"><span class="ion-ios-minus-outline btn-minus f20 dib btnDeleteHarvest"></span></div>
															<div class="dib vm w300 ml20">
															<input type="text" class="form-control" name="yields" placeholder="请输入预计产量,只支持数字"></div>
															<div class="dib vm w300 ml20">
																<input type="text" class="form-control times" id="times1" name="times" readonly="readonly" placeholder="请选择收获时间节点">
															</div>
														</div>
													</div>
													</td>
												</tr>
											</tbody>
										</c:if>
										<tfoot>
											<tr>
												<td style="text-align: center;" colspan="10"><a
													class="btn btn-mini btn-primary" onclick="save();">保存</a> <a
													class="btn btn-mini btn-danger"
													onclick="top.Dialog.close();">取消</a></td>
											</tr>
										</tfoot>
									</table>
								</div>
								<div id="zhongxin2" class="center" style="display: none">
									<br />
									<br />
									<br />
									<br />
									<img src="static/images/jiazai.gif" /><br />
									<h4 class="lighter block green"></h4>
								</div>
							</form>
						</div>
						<!-- /.col -->
					</div>
					<!-- /.row -->
				</div>
				<!-- /.page-content -->
			</div>
		</div>
		<!-- /.main-content -->
	</div>
	<!-- /.main-container -->
	<!-- basic scripts -->
	<!-- 页面底部js¨ -->
	<%@ include file="../index/foot.jsp"%>
	<!-- ace scripts -->
	<script src="static/ace/js/ace/ace.js"></script>
	<!-- inline scripts related to this page -->
	<script src="static/ace/js/bootbox.js"></script>
	<!-- 下拉框 -->
	<script src="static/ace/js/chosen.jquery.js"></script>
	<!--提示框-->
	<script type="text/javascript" src="static/js/jquery.tips.js"></script>
	<script type="text/javascript" src="static/js/common/file_upload.js"></script>
	<script type="text/javascript"
		src="plugins/kindeditor/kindeditor-all.js"></script>
	<script type="text/javascript" src="plugins/kindeditor/lang/zh_CN.js"></script>
	<script type="text/javascript" src="static/layDate-v5.0.9/laydate.js"></script>
	<script type="text/javascript" src="static/js/provincial.municipal.league.js"></script>
</body>
<script>
    //添加收获参数
    $(function () {
    	//$(".aa").html('第1阶段')
        var $harvest = $('.harvest')
        var initNum = 1
        var initNum1 = 1
        $harvest.on('click', '.btnDeleteHarvest', function () {
            var tr = $harvest[0].getElementsByTagName('tr');
            if (tr.length == 1) return;
            var parent = $(this).parents('tr')
            parent.remove()
            initNum -= 1;

            var items = $harvest.children()

            for (var i = 0; i < items.length; i++) {
                items.eq(i).find('.aa').html('第' + (i + 1) + '阶段')
            }
        })
        
        function setHtml(num){
        	var html ='<tr><td class="w100 tr aa">第'+num+'阶段</td><td>'+
        	'<input type="hidden" name="harvestId" value="0" />'+
            '<div class="container-fluid"><div class="row">'+
    		'<div class="dib vm"><span class="ion-ios-minus-outline btn-minus f20 dib btnDeleteHarvest"></span></div>'+
    		'<div class="dib vm w300 ml20"><input type="text" class="form-control" name="yields" placeholder="请输入预计产量,只支持数字" value="">'+
    		'</div><div class="dib vm w300 ml20">'+
    		'<input type="text" class="form-control times" id="times'+num+'" name="times" value="" readonly="readonly" placeholder="请选择收获时间节点">'+
    		'</div></div></div></td></tr>'
    		return html
    	}
        
        
        $('.btnAddHarvest').on('click', function () {
            var initNum = $harvest.children().length
            if (initNum >= 50) return;
            initNum += 1;
            $harvest.append(setHtml(initNum))
            setTimeout(function () {
            	each()
            }, 10)
        })

    });
    


    $(top.hangge());
    //页面初始化完毕后执行此方法

    $(function () {
        var count = $("#count").val();
        if (count != "") {
            var num = $("#num").val();
            $("#countId").val(count);
            $("#stock_num").attr("max", num)
            $("#gS").html("已绑定");
        }
        TAOTAO.kingEditorParams = {
            //指定上传文件参数名称
            filePostName: "uploadFile",
            //指定上传文件请求的url。
            uploadJson: '<%=basePath%>pic/upload',
            //上传类型，分别为image、flash、media、file
            dir: "image",
            extraFileUploadParams: {isCom: "01", width: 800, height: 800, quality: 0.8, end: "view"}
        }

        TAOTAO.kingEditorAutoParams = {
            //指定上传文件参数名称
            filePostName: "uploadFile",
            //指定上传文件请求的url。
            uploadJson: '<%=basePath%>pic/upload',
            //上传类型，分别为image、flash、media、file
            dir: "image",
            extraFileUploadParams: {isCom: "01", width: 200, height: 200, quality: 1, end: "thumb"}
        }

    });
    TAOTAO.initPicUpload($("input[name=picture]").val());
    $('body').on('click', '.imageButton', function () {
        var id = $("#id").val();
        var picture = $("#picture").val();
        var imgsrc = $(this).parent('li').find("img").attr("src");
        var _this = $(this);
        var newPicture = "";
        if (picture.indexOf((imgsrc + ',')) > -1) {
            newPicture = picture.replace((imgsrc + ','), '');
        } else if (picture.indexOf((',' + imgsrc)) > -1) {
            newPicture = picture.replace((',' + imgsrc), '');
        }
        $.ajax({
            url: "<%=basePath%>pic/pictureDelete",
            type: "post",
            async: true,
            dataType: "text",
            data: {"id": id, "newPicture": newPicture, "imgsrc": imgsrc},
            success: function (data) {
                if (data != null) {

                    _this.parent('li').remove();
                    $("#picture").val(newPicture);
                }
                alert(message);
            }, error: function (XMLHttpRequest, textStatus) {
                alealert(textStatus);
            }
        });
    });


    $(".reduction").click(function () {
        var pic = $("#pic").val();
        $("#picture").val(pic);
        TAOTAO.initPicUpload($("input[name=picture]").val());
    });

    function areaGoods() {
        var timeId = $("#timeId").val();
        var specId = $("#specId").val();
        var baseId = $("#base_id").val();
        var countId = $("#countId").val();

        var diag = new top.Dialog();
        diag.Drag = true;
        diag.Title = "绑定区域商品";
        diag.URL = '<%=basePath%>period/bindingGoods.do?specId=' + specId+ '&baseId=' + baseId + '&countId=' + countId;
		diag.Width = 700;
		diag.Height = 400;
		diag.CancelEvent = function() {
			diag.close();
		}, diag.OKEvent = function() {
			var child = diag.innerFrame.contentWindow.document;
			var countId = $(child).find("#ids").val();
			var num = $(child).find("#num").val();
			if (countId != "" || num != "") {
				$("#num").val(num);
				$("#stock_num").attr("max", num)
				$("#countId").val(countId);
				$("#gS").html("已绑定");
			}
			diag.close();
		};//点击确定后调用的方法
		diag.show();
	};

	function save() {
		var countId = $("#countId").val()
		var goodsId = $("#goodsId").val()
		var timeId = $("#timeId").val()
		var specId = $("#specId").val()
		var stock_num = $("#stock_num").val()
		var stock_warn_num = $("#stock_warn_num").val()
		var price = $("#price").val()
		var sale_num = $("#sale_num").val()
		var min_shop_num = $("#min_shop_num").val()
		var max_shop_num = $("#max_shop_num").val()
		var end_use_time = $("#end_use_time").val()
		var equity_cycle = $("#equity_cycle").val()
		var startTime = $("#start_time").val()
		var endTime = $("#end_time").val()
		var picture = $("#picture").val()
		var num = $("#num").val()

		if ($.trim($("#stock_num").val()) == "") {
			alert("请输入库存!")
			return false;
		}
		if (countId != "") {
			if ((stock_num - num) > 0) {
				alert("此商品库存已到达上限!")
				return false;
			}
		} else {
			$("#countId").val("aa");
		}
		if ($.trim($("#stock_warn_num").val()) == "") {
			alert("请输入商品库存警告数量!")
			return false;
		}
		if ($.trim($("#price").val()) == "") {
			alert("请输入销售价!")
			return false;
		}
		if ($.trim($("#sale_num").val()) == "") {
			alert("请输入商品已售数量!")
			return false;
		}
		if ($.trim($("#min_shop_num").val()) == "") {
			alert("请输入最低起售数量!")
			return false;
		}
		if ($.trim($("#max_shop_num").val()) == "") {
			alert("请输入最高起售数量!")
			return false;
		}
		/* 	if ((max_shop_num - min_shop_num) < 0) {
		alert("最高起售数量要大于最低起售数量")
		return false;
	} */
		if ($.trim($("#equity_cycle").val()) == "") {
			alert("请输入权益周期!")
			return false;
		}
		if (equity_cycle <= 0) {
			alert("权益周期不能小于1!")
			return false;
		}
		if ($.trim($("#end_use_time").val()) == "") {
			alert("请选择商品截止使用时间!")
			return false;
		}
		

		if (countId == "" || countId == "aa") {
			bootbox.confirm("还未绑定区域商品，确定提交吗？", function(result) {
				if (result) {
					$("#goodsForm").submit();
					$("#zhongxin").hide();
					$("#zhongxin2").show();
				}
			});
		} else {
			$("#goodsForm").submit();
			$("#zhongxin").hide();
			$("#zhongxin2").show();
		}
	}

	/* laydate({
		elem : '#times1',
		format : 'YYYY-MM',
		min : laydate.now(),
		max : '2099-06',
		istime : true,
		istoday : true,
		choose : function(datas) {
		}
	});

	laydate({
		elem : '#end_use_time',
		format : 'YYYY-MM-DD hh:mm:ss',
		min : laydate.now(),
		max : '2099-06-16 23:59:59',
		istime : true,
		istoday : true,
		choose : function(datas) {
		}
	});
 */
	/* function setTime(ele) {
		var time = '';
		if (ele == '#times2') {
			time = $("#times1").val();
		} else if (ele == '#times3') {
			time = $("#times2").val();
		}
		laydate({
			elem : ele,
			format : 'YYYY-MM',
			min : time,
			max : '2099-06',
			istime : true,
			istoday : true,
			choose : function(datas) {
			}
		});
	} */
	
	
	laydate.render({ 
	  elem: '#end_use_time',
	  type: 'datetime'
	});
	
	
	var dateArr =[]
	
	var defaultLimit = {
			min:Date.now(),
			max: '2099-06-01'
	}
	
     function setTime(id) {
        return {
            elem: id,
            //format: 'yyyy-MM',
            min: defaultLimit.min,
            max: defaultLimit.max,
            type: 'month',
            done: function (value, date, endDate) {
                var index = this.elem.selector.slice(-1)-1
                var status = contrastTime(value,index)
                if(!status){
                	alert('请选择正确时间!')
                	$('.times').eq(index).val('')
                }
            }

        }

    }
	
    // 对比时间
    function contrastTime(current,index){
    	var $times = $('.times')
    	var status = false
        var prevDate = index!==0?$times.eq(index-1).val():false;
        var nextDate = index!==dateArr.length-1?$times.eq(index+1).val():false;
        var dateTime = current
        
        
        console.log(prevDate,dateTime,nextDate)
        
        prevDate = !!prevDate?parsingDate(prevDate):false;
        
        nextDate = !!nextDate?parsingDate(nextDate):false;
        
        dateTime = !!dateTime?parsingDate(dateTime):false;
        
        //console.log(prevDate,dateTime,nextDate)
        
        if(prevDate&&nextDate){
        	status = dateTime>prevDate&&dateTime<nextDate?true:false
        }else if(!prevDate&&!nextDate){
        	status = true
        }else if(!prevDate){
        	status = dateTime<nextDate?true:false
        }else if(!nextDate){
        	status = dateTime>prevDate?true:false
        }
        return status
    }

    // 解析日期
    function parsingDate(value){
    	if(value==='')return false;
    	var dateArr = value.split('-');
    	var year = dateArr[0]
    	var month = dateArr[1]
    	return new Date(year,month).getTime()
    }
    
    // 绑定 日期
    
    each()
    
    function each(){
    	dateArr = []
        $('.times').each(function(index,ele){
        	var id = '#'+ele.id
        	dateArr.push(laydate.render(setTime(id)))
        })
    }
    
    
    
</script>
</html>
